package com.ctg.behavior.calc.controller.addictions;

import java.io.File;

import com.ctg.behavior.common.addictions.CtAddictionsCalcRequest;
import com.ctg.behavior.common.addictions.CtAddictionsCalcResult;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.ctg.behavior.calc.example.ExampleAddictionsReportResult;
import com.ctg.behavior.common.CtgResult;
import com.ctg.behavior.common.addictions.CtAddictionsCalcBody;
import com.ctg.behavior.common.addictions.CtAddictionsCalcData;

import lombok.extern.slf4j.Slf4j;

/*分布分析*/
@Slf4j
@RestController
@RequestMapping("/api/addictions")
public class AddictionsController {

	@Value("${simulator.path}")
	private String simlutorPath;

	@PostMapping("/report")
	public CtAddictionsCalcResult report(@RequestBody CtAddictionsCalcRequest body) throws Exception {
		CtAddictionsCalcResult result = new CtAddictionsCalcResult();

		log.info("body", JSON.toJSONString(body));

		String filePath = simlutorPath + "/addictions/report";
		FileUtils.forceMkdir(new File(filePath));

		File bodyFile = new File(filePath + "/addictions.json");

		String bodyString = null;
		if (bodyFile.exists()) {
			bodyString = FileUtils.readFileToString(bodyFile, "UTF-8");
		} else {
			if (body.getReq().getByField().equals("event._Anything._lib")&&body.getReq().getEventId().equals("successGroup")){
				bodyString = ExampleAddictionsReportResult.example02;
			}else{
				bodyString = ExampleAddictionsReportResult.example03;
			}
		}
		result = JSON.parseObject(bodyString, CtAddictionsCalcResult.class);

		return result;
	}

	@PostMapping("/reportTMU")
	public CtgResult report(@RequestBody CtAddictionsCalcData body) throws Exception {
		CtgResult result = new CtgResult();

		String filePath = simlutorPath + "/addictions/report";
		FileUtils.forceMkdir(new File(filePath));
		
		File targetFile = new File(filePath + "/addictions.json");

		FileUtils.writeStringToFile(targetFile, JSON.toJSONString(body), "UTF-8");

		result.setErrorMessage("report response body updload successfully!(test mode)");

		return result;
	}

}
